package com.twohand.admin.Service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import com.twohand.admin.Dto.BatchChangeMoneyDto;
import com.twohand.admin.Dto.OrderListQueryDto;
import com.twohand.admin.Entity.Bill;
import com.twohand.admin.Entity.Order;
import com.twohand.admin.Entity.Shop;
import com.twohand.admin.Entity.User;
import com.twohand.admin.Mapper.BillMapper;
import com.twohand.admin.Mapper.OrderMapper;
import com.twohand.admin.Mapper.ShopMapper;
import com.twohand.admin.Service.OrderService;
import com.twohand.admin.Service.ShopService;
import com.twohand.admin.Service.UserService;
import com.twohand.admin.Util.JwtUtil;
import com.twohand.admin.Util.PageResponse;
import com.twohand.utils.Response.BaseException;
import com.twohand.utils.Response.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    BillMapper billMapper;
    @Autowired
    ShopMapper shopMapper;
    @Autowired
    ShopService shopService;
    @Autowired
    UserService userService;
    public Logger log = LoggerFactory.getLogger(OrderServiceImpl.class);
    @Override
    public PageResponse<Order> orderList(OrderListQueryDto orderListQueryDto) {
        List<Bill> bills = getCurrentUserBids();
        List<String> billList = null;
        if(bills!=null&&bills.size()>0){
            billList = bills.stream().map(Bill::getBillNo).collect(Collectors.toList());
        }
        PageHelper.startPage(orderListQueryDto.getPageNum(),orderListQueryDto.getPageSize());
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        String orderId = orderListQueryDto.getOrderId();
        String orderNo = orderListQueryDto.getOrderNo();
        String bid = orderListQueryDto.getBid();
        if(StringUtil.isNotEmpty(orderId)){
            queryWrapper.like("order_id",orderId);
        }
        if(StringUtil.isNotEmpty(orderNo)){
            queryWrapper.like("order_no",orderNo);
        }
        if(StringUtil.isNotEmpty(bid)){
            queryWrapper.like("bid",bid);
        }
        if(billList!=null&&billList.size()>0){
            queryWrapper.in("bid",billList);
        }
        List <Order> qrcodeList = orderMapper.selectList(queryWrapper);
        PageInfo<Order> swipePageInfo = new PageInfo<>(qrcodeList);
        return new PageResponse<Order>(swipePageInfo,qrcodeList);
    }

    @Override
    public Boolean addOrder(Order order) {
        String bid = order.getBid();
        LambdaQueryWrapper<Bill> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Bill::getBillNo,bid);
        Bill bill = billMapper.selectOne(lambdaQueryWrapper);
        if(bill==null){
            throw new BaseException(500,"账单:"+bid+"不存在");
        }
        String orderNo = order.getOrderNo();
        List<Order> order1 = orderMapper.checkOrder(orderNo);
        if(order1.size()!=0){
            throw new BaseException(500,"订单编号重复,订单编号:"+orderNo);
        }
        updateShopForBid(bid);
        return orderMapper.insert(order) > 0;
    }
    /*
    * 三方订单导入
    * 根据店铺名和平台自动创建账单
    * */
    @Override
    public Boolean importOrder2(Order order) {
        String bid = order.getBid();
        LambdaQueryWrapper<Bill> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Bill::getBillNo,bid);
        Bill bill = billMapper.selectOne(lambdaQueryWrapper);
        if(bill==null){
            /*查询是否存在对应的店铺*/
            LambdaQueryWrapper<Shop> shopLambdaQueryWrapper = new LambdaQueryWrapper<>();
            shopLambdaQueryWrapper.eq(Shop::getShopName,order.getShopName())
                    .eq(Shop::getPlatform,order.getPlatform());
            Shop shop = shopMapper.selectOne(shopLambdaQueryWrapper);
            if(shop==null){
//                throw new BaseException(500,"店铺:"+order.getShopName()+(order.getPlatform()==1?"--美团":"--饿了么")+"不存在");
                throw new BaseException(500, "店铺:" + order.getShopName() +
                        (order.getPlatform() == 1 ? "--美团" :
                                order.getPlatform() == 2 ? "--饿了么" :
                                        order.getPlatform() == 3 ? "--京东秒送" : "--未知平台") +
                        "不存在");
            }
            Integer shopId = shop.getId();
            Bill autoBill = new Bill();
            autoBill.setBillNo(bid);
            autoBill.setStatus(0);
            autoBill.setActiveDate(order.getActiveDate());
            autoBill.setShopId(shopId);
            billMapper.insert(autoBill);
        }
        String orderNo = order.getOrderNo();
        List<Order> order1 = orderMapper.checkOrder(orderNo);
        if(order1.size()!=0){
            throw new BaseException(500,"订单编号重复,订单编号:"+orderNo);
        }
        updateShopForBid(bid);
        return orderMapper.insert(order) > 0;
    }

    @Override
    public Boolean changeOrder(Order order) {
        updateShopForBid(order.getBid());
        return orderMapper.updateById(order) > 0;
    }

    @Override
    public Boolean delOrder(Integer id) {
        Order order = orderMapper.selectById(id);
        updateShopForBid(order.getBid());
        return orderMapper.deleteById(id) > 0;
    }

    @Override
    public List<Order> getOrderByBillNo(String billNo) {
        //构造查询器
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("bid",billNo);
        List<Order> orderList = orderMapper.selectList(queryWrapper);
        return orderList;
    }

    @Override
    public Object BatchAddOrder(List<Order> orderList) {
        if(orderList.size()==0){
            throw  new BaseException(500,"店铺订单数据为空！");
        }
        log.info("添加的orderList:{}",orderList);
        Integer  success = orderMapper.batchInsert(orderList);
        log.info("成功导入{}条订单数据!",success);
        return new Response(203,"成功导入"+success+"条订单数据!",success>0);
    }

    @Async
    @Override
    public void updateShopForBid(String bid) {
        try{
            LambdaQueryWrapper<Bill> bwrap = new LambdaQueryWrapper<>();
            bwrap.eq(Bill::getBillNo,bid);
            Bill bill = billMapper.selectOne(bwrap);
            if(bill!=null){
                LambdaQueryWrapper<Shop> swrap = new LambdaQueryWrapper<>();
                swrap.eq(Shop::getId,bill.getShopId());
                Shop shop = shopMapper.selectOne(swrap);
                if(shop!=null){
                    shopService.updateUrlIsNotGen(shop.getShopName(),shop.getId());
                }
            }
        }catch (Exception e){

        }
    }

    @Override
    public Boolean updateBlock(String orderNo) {
        //1.查找订单
        LambdaQueryWrapper<Order> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Order::getOrderNo,orderNo);
        Order order = orderMapper.selectOne(lambdaQueryWrapper);
        Integer isBlock = order.getIsBlock();
        if(isBlock==0){
            isBlock = 1;
        }else {
            isBlock = 0;
        }
        order.setIsBlock(isBlock);
        return orderMapper.updateById(order) > 0;
    }
    @Override
    public List<Integer> getCurrentUserShopIds() {
        User user = JwtUtil.getCurrentUser();
        User user1 = userService.getUserById(user.getId());
        if(user1.getSid()!=0){
            List<Integer> list =  shopService.getSalesShop(user1.getSid(),null,null).stream().map(Shop::getId).collect(Collectors.toList());
            return list;
        }
        return null;
    }
    @Override
    public List<Bill> getCurrentUserBids() {
        List<Integer> shopIds = getCurrentUserShopIds();
        if(shopIds!=null&&shopIds.size()>0){
            List<Bill> billList = billMapper.getList(null,null,null,null,null,null,null,shopIds);
            return billList;
        }
        return null;
    }

    @Override
    public Boolean batchChangeMoney(BatchChangeMoneyDto batchChangeMoneyDto) {
        List<String> ids = batchChangeMoneyDto.getIds();
        if(ids.size()==0){
            throw new BaseException(500,"未勾选需要修改的订单！");
        }
        return orderMapper.batchChangeMoney(ids,batchChangeMoneyDto.getMoney()) > 0;
    }
   @Override
    public Boolean batchChangeBid(BatchChangeMoneyDto batchChangeMoneyDto) {
        List<String> ids = batchChangeMoneyDto.getIds();
        if(ids.size()==0){
            throw new BaseException(500,"未勾选需要修改的订单！");
        }
        return orderMapper.batchChangeBid(ids,batchChangeMoneyDto.getBid()) > 0;
    }


}
